//
//  TextUploadViewController.m
//  PhotoSelector
//
//  Created by jerry on 2017/4/19.
//  Copyright © 2017年 jerry. All rights reserved.
//

#import "TextUploadViewController.h"
#import "EvaluateViewController.h"
#import <AFNetworking.h>
#import "AppDelegate.h"

#define url @"http://127.0.0.1:8080/app"

@interface TextUploadViewController ()<UIPickerViewDelegate,UIPickerViewDataSource,UITextViewDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *prName;
@property (weak, nonatomic) IBOutlet UITextField *prPrice;
@property (weak, nonatomic) IBOutlet UITextField *prCategory;

@property (weak, nonatomic) IBOutlet UITextField *prDiscount;
@property (weak, nonatomic) IBOutlet UITextView *prDiscribe;
@property (weak, nonatomic) IBOutlet UILabel *prDiscribe_check;
@property(nonatomic,strong)UIPickerView *cityPickerView;
@property(nonatomic,strong)UIToolbar *myToolbar;

@end

@implementation TextUploadViewController{
    NSInteger rowCache;
    NSInteger *index;
    NSMutableArray *pickerData;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self getCategory];// Do any additional setup after loading the view.
    self.prCategory.delegate=self;
//    self.prCategory.inputView = self.cityPickerView;
//    self.prCategory.inputAccessoryView = self.myToolbar;
    self.prDiscribe.delegate = self;
    self.prDiscribe_check.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (pickerData==nil) {
        [self getCategory];
        return NO;
    }else{
        [self loadPickerViewAndToolbar];
        self.prCategory.inputView = self.cityPickerView;
        self.prCategory.inputAccessoryView = self.myToolbar;
        return YES;
    }
}
- (IBAction)toImageUpload:(id)sender {
    if (_prName.text==nil) {
        [self AlerShow:@"" :@"产品名称不能为空"];
    }else if (_prPrice==nil){
        [self AlerShow:@"" :@"产品价格不能为空"];
    }else if (_prDiscount==nil){
        [self AlerShow:@"" :@"产品折扣不能为空"];
    }else if (_prCategory==nil){
        [self AlerShow:@"" :@"产品分类不能为空"];
    }else if (_prDiscribe==nil){
        [self AlerShow:@"" :@"产品介绍不能为空"];
    }else{
        [self uploadInfo];
    }
}
-(void)uploadInfo{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSDictionary *idandpass = @{@"phone":delegate.phone,@"name":delegate.name,@"pname":_prName.text,@"price":_prPrice.text,@"discount":_prDiscount.text,@"introduce":_prDiscount.text,@"categoryID":[NSString stringWithFormat:@"%@",[pickerData[rowCache] objectForKey:@"categoryID"]]};
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:idandpass options:NSJSONWritingPrettyPrinted error:nil];
    NSString *test = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSDictionary *paramDic=@{@"method":@"uploadInfo",@"param":test};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", @"text/plain", nil];
    [manager POST:url parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *status = [responseObject objectForKey:@"status"];
        if (status.integerValue == -1) {
            NSDictionary *data = [responseObject objectForKey:@"data"];
            NSString *prID = [data objectForKey:@"productID"];
            EvaluateViewController *evaVC = [[EvaluateViewController alloc] init];
            evaVC.productID=prID;
            evaVC.categoryID=[pickerData[rowCache] objectForKey:@"categoryID"];
            [self.navigationController pushViewController:evaVC animated:evaVC];
        }else{
            [self AlerShow:@"数据上传失败" :[responseObject objectForKey:@"message"]];
        }
        NSLog(@"post success:%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self AlerShow:@"数据上传失败":@"请检测您的网络"];
    }];
}

-(void)getCategory{
    AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    NSDictionary *idandpass = @{@"phone":delegate.phone,@"name":delegate.name};
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:idandpass options:NSJSONWritingPrettyPrinted error:nil];
    NSString *test = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSDictionary *paramDic=@{@"method":@"getCategory",@"param":test};
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", @"text/plain", nil];
    [manager POST:url parameters:paramDic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSString *status = [responseObject objectForKey:@"status"];
        if (status.integerValue == -1) {
            pickerData= [responseObject objectForKey:@"data"];
        }else{
            [self AlerShow:@"申请分类数据失败" :[responseObject objectForKey:@"message"]];
        }
        NSLog(@"post success:%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self AlerShow:@"申请分类数据失败":@"请检测您的网络"];
    }];
}

-(void)AlerShow:(NSString *) Title :(NSString *) Text{
    UIAlertController *alertContro = [UIAlertController alertControllerWithTitle:Title message:Text preferredStyle:UIAlertControllerStyleAlert];
    [alertContro addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertContro animated:YES completion:nil];
}

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return pickerData.count;
}

//-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
//    return [_nameArray objectAtIndex:row];
//}

-(void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length>0) {
        self.prDiscribe_check.hidden = YES;
    } else {
        self.prDiscribe_check.hidden = NO;
    }
}

- (void)loadPickerViewAndToolbar {
    
    // --- pickerView ---
    

    
    // 创建pickerView
    self.cityPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height, self.view.bounds.size.width, 200)];
    self.cityPickerView.backgroundColor = [UIColor lightGrayColor];
    
    // 代理
    self.cityPickerView.delegate = self;
    self.cityPickerView.dataSource = self;
    
    // --- tool bar ---
    
    UIBarButtonItem *doneBBI = [[UIBarButtonItem alloc]
                                initWithTitle:@"确定"
                                style:UIBarButtonItemStyleDone
                                target:self
                                action:@selector(doneClick)];
    
    UIBarButtonItem *cancelBBI = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelClick)];
    UIBarButtonItem *flexibleBBI = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    self.myToolbar = [[UIToolbar alloc]initWithFrame:
                      CGRectMake(0, self.view.frame.size.height-
                                 self.cityPickerView.frame.size.height-20, self.view.bounds.size.width, 40)];
    [self.myToolbar setBarStyle:UIBarStyleBlackOpaque];
    NSArray *toolbarItems = [NSArray arrayWithObjects:cancelBBI, flexibleBBI, doneBBI,nil];
    [self.myToolbar setItems:toolbarItems];
    
}


- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component {
    return 30;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
    return self.view.bounds.size.width;
}
/**
 //- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
 //    NSString *str = [NSString stringWithString:_nameArray[row]];
 //    return str;
 //}
 */// <???>不知道有什么用?
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    if (!view) {
        view = [[UIView alloc] init];
    }
    UILabel *textlabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 30)];
    textlabel.textAlignment = NSTextAlignmentCenter;
    textlabel.text = [pickerData[row] objectForKey:@"name"];
    textlabel.font = [UIFont systemFontOfSize:19];
    [view addSubview:textlabel];
    return view;
}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    rowCache = row;
    self.prCategory.text = [pickerData[row] objectForKey:@"name"];
}

- (void)doneClick {
    if ( [self.prCategory isFirstResponder] ) {
        [self.prCategory resignFirstResponder];
    }
}

- (void)cancelClick {
    [self doneClick];
}

- (IBAction)writeDone:(UITextField *)sender {
    [sender resignFirstResponder];
}

-(IBAction)backgroundTap:(id)sender{
    [self.prName resignFirstResponder];
    [self.prPrice resignFirstResponder];
    [self.prDiscount resignFirstResponder];
    [self.prDiscribe resignFirstResponder];
    [self.prCategory resignFirstResponder];
}

-(void)textViewDidEndEditing:(UITextView *)textView{
    [textView resignFirstResponder];
}


@end
